package com.dhecp.project.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.config.Global;
import com.dhecp.common.core.controller.BaseController;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.common.utils.file.FileUploadUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.layui.TreeDataModel;
import com.dhecp.core.layui.TreeDataUtil;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.service.ButtonStateService;
import com.dhecp.project.system.domain.SysDataFolder;
import com.dhecp.project.system.domain.SysUserInfo;
import com.dhecp.project.system.service.SysDataFolderService;
import com.dhecp.project.system.service.SysUserInfoService;

/**
 * 资料文件夹信息
 */
@Controller
@RequestMapping("/system/datafolder")
public class SysDataFolderController extends BaseController {
    private String prefix = "system/datafolder";
    private String moduleTable = ModuleTable.DATAFOLDER;

    @Autowired
    private SysDataFolderService datafolderService;
    
    @Autowired
	private ButtonStateService buttonStateService;
    
    @Autowired
    private SysUserInfoService userInfoService;

    @Autowired
    private TreeDataUtil treeDataUtil;

//    @RequiresPermissions("system:datafolder:view")
    @GetMapping()
    public ModelAndView datafolder(@RequestParam Map<String, Object> params)
    {
    	ModelAndView mv = this.getModelAndView();
    	Map<String, Object> buttonState = new HashMap<String, Object>();	//按钮状态：（可用：enable，禁用：disable，隐藏：hidden）
        Map<String, Object> paramsButton = new HashMap<String, Object>();
        paramsButton.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try{
        	buttonState = buttonStateService.getButtonStateObjectForUser(paramsButton);	//按钮状态：（可用：enable，禁用：disable，隐藏：hidden）
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        String uploadUrl = FileUploadUtils.getUploadUrl();
        String fileViewUrl = FileUploadUtils.getFileViewUrl();
        mv.addObject("uploadUrl", uploadUrl);
        mv.addObject("fileViewUrl", fileViewUrl);
        mv.addObject("createUser", ShiroUtils.getMandatorId());
        mv.addObject("buttonState", TypeUtils.mapToJson(buttonState));	//按钮状态：（可用：enable，禁用：disable，隐藏：hidden）
    	mv.addObject("maxFileSize",Global.getConfig("spring.servlet.multipart.max-file-size"));	//服务器上传文件最大值
        mv.addObject("ajaxResult", ajaxResult);
        mv.setViewName(prefix + "/datafolder");
    	return mv;
    }
    
//    @RequiresPermissions("system:datafolder:list")
    @RequestMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
        List<SysDataFolder> list = new ArrayList<SysDataFolder>();
        try {
            list = datafolderService.queryDataFolder(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());            
        }
        return getDataTable(list);
    }
    /**
     * 打开资料文件夹新增
     * @param params
     * @return ModelAndView
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:datafolder:add")
    @GetMapping("/datafoldersort")
    public ModelAndView datafolderSort(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
        mv.addObject("pguid", params.get("pguid").toString());
        mv.setViewName(prefix + "/datafoler_sort");
        return mv;
    }
    /**
     * 打开资料文件夹新增
     * @param params
     * @return ModelAndView
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:datafolder:add")
    @GetMapping("/add")
    public Object datafolderAdd(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
        if (mv.isEmpty()){
            mv = this.gotoModelAndViewErrorPage(params, "pguid","上级文件夹唯一值（guid），若新增的是顶级则默认（root）");
        }
        if (mv.isEmpty()){
            String folderNameSelected;	//选中的文件夹节点名称
            if (params.get("folderNameSelected") != null && params.get("folderNameSelected") != ""){
                folderNameSelected = params.get("folderNameSelected").toString();
            }else{
                folderNameSelected = "未知节点";
            }
            AjaxResult ajaxResult = new AjaxResult();
            if ("company".equals(params.get("orgKind").toString().toLowerCase()) && "dept".equals(params.get("porgKind").toString().toLowerCase())){
                ajaxResult = AjaxResult.error("不能在部门中添加公司。");
            }else{
                ajaxResult = AjaxResult.success("参数合理。");
            }
            mv.addObject("ajaxResult", ajaxResult);
            mv.addObject("folderNameSelected", folderNameSelected);
            mv.addObject("pguid", params.get("pguid").toString());
            mv.setViewName(prefix + "/datafolder_add");
        }
        return mv;
    }

    /**
     * 打开资料文件夹修改
     * @param params
     * @return ModelAndView
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:datafolder:edit")
    @GetMapping("/edit")
    public ModelAndView datafolderEdit(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
        if (mv.isEmpty()){
            mv = this.gotoModelAndViewErrorPage(params, "guid","文件夹唯一值");
        }
        if (mv.isEmpty()){
            AjaxResult ajaxResult = new AjaxResult();
            try{
                SysDataFolder datafolder = datafolderService.queryDataFolderByGuid(params.get("guid").toString());
                if (datafolder == null){
                    ajaxResult = AjaxResult.error("没有符合条件的数据。");
                }else{
                    ajaxResult = AjaxResult.success("查询成功。");
                }
                mv.addObject("datafolder", datafolder);
                mv.addObject("pguid", datafolder.getPguid());
            }catch(Exception e){
                ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
            }
            mv.addObject("ajaxResult", ajaxResult);
            mv.setViewName(prefix + "/datafolder_add");
        }
        return mv;
    }

    /**
     * 1、打开资料文件夹管理者分配页面(pagetype=managers)
     * 2、打开部门分配用户页面(pagetype=users)
     * @param params
     * @return ModelAndView
     * @author DH-Xxj
     */
    @GetMapping("/orgusersadd")
    public ModelAndView datafolderUsersAdd(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
        if (mv.isEmpty()){
            mv = this.gotoModelAndViewErrorPage(params, "pagetype","页面类型：managers（分配管理者），users（分配用户）");
        }
        if (mv.isEmpty()){
            mv = this.gotoModelAndViewErrorPage(params, "guid","文件夹唯一值");
        }
        if (mv.isEmpty()){
            String pagetype = params.get("pagetype").toString();
            String pagetitle = "managers".equals(pagetype)?"分配管理者":"分配用户";
            mv.addObject("pagetype", pagetype);
            mv.addObject("pagetitle", pagetitle);
            mv.setViewName(prefix + "/orgusers_add");
        }
        return mv;
    }
    /**
     * 通过guid查询单条记录
     * @param guid
     * @return MessageModel
     * @throws Exception
     * @author DH-Xxj
     */
    @RequestMapping("/lineguid")
    @ResponseBody
    public AjaxResult datafolderlineJsonByGuid(@RequestParam(required = false, defaultValue = "no", value = "guid") String guid)
    {
        AjaxResult ajaxResult = new AjaxResult();
        try{
            SysDataFolder datafolder = datafolderService.queryDataFolderByGuid(guid);
            if (datafolder == null){
                ajaxResult =  AjaxResult.error("没有符合条件的数据。");
            }else{
                ajaxResult = AjaxResult.success("查询成功。", datafolder);
            }
        }catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 获取资料文件夹树
     * @param params
     * @return List
     * @throws Exception
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:datafolder:list")
    @RequestMapping("/listtreejson")
    @ResponseBody
    public Object datafolderTreeJson(@RequestParam Map<String, Object> params) {
        List<TreeDataModel> treeDataModelList = new ArrayList<TreeDataModel>();
        try{
            treeDataModelList = datafolderService.queryDataFolderTree(params);
            treeDataModelList = treeDataUtil.dealTreeDataModel(treeDataModelList,treeDataModelList.get(0).getMaxlevels());
        }catch(Exception e){
            return treeDataModelList;
        }
        return treeDataModelList;
    }

    /**
     * 查询选中文件夹节点的管理者列表
     * @param params
     * @return GridDataModel
     * @throws Exception
     * @author DH-Xxj
     */
    @RequestMapping("/managersAlllistjson")
    @ResponseBody
    public TableDataInfo datafolderManagersAllListJson(@RequestParam Map<String, Object> params){
        List<SysUserInfo> list = new ArrayList<SysUserInfo>();
        try {
            list = userInfoService.queryManagersAllListByGuid(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString()); 
        }
        return getDataTable(list);
    }
    
    /**
     * 查询调入资料文件夹对象
     * @param params
     * @return TableDataInfo
     * @author DH-Xxj
     */
    @RequestMapping("/orgObject")
    @ResponseBody
    public TableDataInfo datafolderObject(@RequestParam Map<String, Object> params){
    	if (params.get("moduleTable") == null || params.get("moduleTable") == ""){
        	params.put("moduleTable", moduleTable);
    	}
        List<SysDataFolder> list = new ArrayList<SysDataFolder>();
        try {
            list = datafolderService.queryDataFolderObject(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString()); 
        }
        return getDataTable(list);
    }

    /**
     * 新增文件夹节点（公司、部门）——数据提交
     * @param params
     * 		必要参数：pguid（上级文件夹唯一值guid，顶级默认值（'root'））
     * 		必要参数：folderName（新增文件夹名称）
     * @return MessageModel
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:datafolder:add")
    @Log(title = "资料文件夹", businessType = BusinessType.INSERT)
    @PostMapping("/addpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult datafolderAddPost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= datafolderService.insertDataFolder(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }


    /**
     * 分配管理者——数据提交
     * @param guid 必要参数： 要分配管理者的文件夹唯一值
     * @param userList 必要参数：对应实体类的json格式字符串(orgid:用户编号)
     * @return MessageModel
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:datafolder:add")
    @Log(title = "资料文件夹分配管理用户", businessType = BusinessType.INSERT)
    @PostMapping("/addorgmanagerspost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult datafolderAddOrgManagersPost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= datafolderService.insertOrgManagersByGuid(params);
        }catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 通过orgPathAll删除文件夹及其子树
     * @param params
     * 		必要参数：orgPathAll（要删除的文件夹全路径）
     * @return MessageModel
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:datafolder:delete")
    @Log(title = "资料文件夹", businessType = BusinessType.DELETE)
    @PostMapping("/deletesubtreepost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult datafolderDeleteSubtreePost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= datafolderService.deleteSubtreeByOrgPathAll(params);
        }catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 删除指定的管理者
     * @param params
     * 		必要参数：guid（要删除管理者的文件夹唯一值）
     * 		必要参数：orgid（要删除的管理者用户编号）
     * @return MessageModel
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:datafolder:delete")
    @Log(title = "资料文件夹删除指定的管理者", businessType = BusinessType.DELETE)
    @PostMapping("/deleteorgmanagerspost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult datafolderDeleteOrgManagersPost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= datafolderService.deleteOrgManagersByGuid(params);
        }catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 通过guid修改文件夹名称
     * @param params
     * 		必要参数：guid（要修改的文件夹唯一值）
     * 		必要参数：folderName（修改后的文件夹名称）
     * @return MessageModel
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:datafolder:edit")
    @Log(title = "资料文件夹", businessType = BusinessType.UPDATE)
    @PostMapping("/editorgnamepost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult datafolderEditFolderNamePost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= datafolderService.updateFolderNameByGuid(params);
        }catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 通过guid修改文件夹行号
     * @param params
     * 		必要参数：guid（要修改的文件夹唯一值）
     * 		必要参数：iid（修改后的行号）
     * @return MessageModel
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:datafolder:edit")
    @Log(title = "通过guid修改文件夹行号", businessType = BusinessType.UPDATE)
    @PostMapping("/updateiidbyguid")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult baseInfoBdefaultEditPost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= datafolderService.updateIidByGuid(params);
        }catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 查询所有部门
     * @param params
     * @return TableDataInfo
     * @author kimiloo
     */
//    @RequiresPermissions("system:datafolder:list")
    @RequestMapping("/listbydepe")
    @ResponseBody
    public TableDataInfo listbydepe(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
        List<SysDataFolder> list = new ArrayList<SysDataFolder>();
        try {
            list = datafolderService.queryDeptInfo(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());            
        }
        return getDataTable(list);
    }
}
